package com.dreamlin.app.base.ui

import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

class BaseAdapter<T>(private var mData: List<T>, @LayoutRes var layoutId: Int) :
    RecyclerView.Adapter<BaseViewHolder<T>>() {

    private lateinit var mListener: AdapterListener<T>

    fun setListener(listener: AdapterListener<T>) {
        this.mListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T> {
        val view = LayoutInflater.from(parent.context)
            .inflate(layoutId, parent, false)
        return BaseViewHolder(view)
    }

    override fun getItemCount(): Int {
        return mData?.size
    }

    override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
        mListener?.convert(holder, mData?.get(position))

    }

    override fun onViewRecycled(holder: BaseViewHolder<T>) {
        super.onViewRecycled(holder)
    }

    override fun onFailedToRecycleView(holder: BaseViewHolder<T>): Boolean {
        return super.onFailedToRecycleView(holder)
    }

}

class BaseViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {

    private val views: SparseArray<View> = SparseArray()

    fun <V> getView(@IdRes id: Int): V {
        var view = views[id]
        view = view ?: itemView.findViewById(id)
        views.put(id, view)
        return view as V
    }

    fun setText(@IdRes id: Int, text: String) {
        var view = views[id]
        if (view == null)
            view = itemView.findViewById(id)
        if (view is TextView) view.text = text
    }

    open fun bindItem(bean: T) {

    }
}

interface AdapterListener<T> {
    fun convert(holder: BaseViewHolder<T>, bean: T)
}
